package com.gzsxy.Test;

/**
 * 用不同的方法去实现1到100的累加和；
 */
public class Digui {


    /**
     * 递归算法
     *
     * @param i
     * @return
     */
    public int sum(int i) {
        if (i == 1) {
            return 1;
        } else {
            return i + sum(i - 1);
        }
    }


    /**
     * for循环
     */
    public int test1() {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            sum = i + sum;
        }
        return sum;
    }


    /**
     * while
     *
     * @return
     */
    public int test2() {
        int i = 0;
        int sum = 0;
        while (i <= 100) {
            sum = sum + i;
            i++;
        }
        return sum;
    }


    /**
     * do while
     *
     * @return
     */
    public int test3() {
        int i = 0;
        int sum = 0;
        do {
            sum = sum + i;
            i++;
        } while (i <= 100);
        return sum;
    }


    public static void main(String[] args) {
        Digui digui = new Digui();
        System.out.println("1+...+100 =" + digui.sum(100));
        System.out.println("test1=" + digui.test1());
        System.out.println("test2=" + digui.test2());
        System.out.println("test3=" + digui.test3());
    }
}
